package cn.schoolwow.quickdao.module.database.dql.response.flow.common.resultSet;

import cn.schoolwow.quickdao.domain.QuickDAOConfig;
import cn.schoolwow.quickdao.domain.database.dql.condition.QueryColumnTypeMapping;
import cn.schoolwow.quickdao.domain.entity.Property;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

import java.util.Map;

public class MatchQueryColumnTypeMappingFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        Property[] resultSetPropertyArray = (Property[]) flowContext.checkData("resultSetPropertyArray");
        Map<String,Class> queryColumnTypeMap = (Map<String, Class>) flowContext.getData("queryColumnTypeMap");

        if(null!=queryColumnTypeMap){
            flowContext.log("根据queryColumnTypeMap设置字段类型");
            for(Property resultSetProperty:resultSetPropertyArray){
                if(queryColumnTypeMap.containsKey(resultSetProperty.columnLabel)||queryColumnTypeMap.containsKey(resultSetProperty.column)){
                    resultSetProperty.clazz = queryColumnTypeMap.get(resultSetProperty.columnLabel);
                }
            }
        }

        QuickDAOConfig quickDAOConfig = flowContext.checkInstanceData(QuickDAOConfig.class);
        QueryColumnTypeMapping queryColumnTypeMapping = (QueryColumnTypeMapping) flowContext.getData("queryColumnTypeMapping");
        if(null==queryColumnTypeMapping){
            queryColumnTypeMapping = quickDAOConfig.entityOption.queryColumnTypeMapping;
        }
        if(null!=queryColumnTypeMapping){
            flowContext.log("根据queryColumnTypeMapping设置字段类型");
            for(Property resultSetProperty:resultSetPropertyArray){
                Class type = queryColumnTypeMapping.columnTypeMapping(resultSetProperty);
                if (null != type) {
                    resultSetProperty.clazz = type;
                }
            }
        }
    }

    @Override
    public String name() {
        return "匹配字段列映射";
    }
}
